<template>
    <div class="management-container">
      <div class="sidebar">
        <h2>管理系统</h2>
        <nav>
          <button @click="currentView = 'products'">商品管理</button>
          <button @click="currentView = 'users'">用户管理</button>
          <button @click="currentView = 'orders'">订单管理</button>
        </nav>
      </div>
      <div class="content">
        <div v-if="currentView === 'products'">
          <div style="display: flex; align-items: center; justify-content: space-between;">
          <h3>商品管理</h3>
          <button class="add-product-button" @click="openAddModal">添加商品</button>
        </div>
          <table>
            <thead>
            <tr>
              <th>商品图片</th>
              <th>商品名称</th>
              <th>价格</th>
              <th>描述</th>
              <th>类别</th>
              <th>图片路径</th>
              <th>操作</th>
            </tr>
            </thead>
            <tbody>
                <tr v-for="product in products" :key="product.id">
                    <td class="product-image">
                        <img v-if="product.image" :src="product.image" :alt="product.name" style="width: 100px; height: 100px;">
                    </td>
                    <td>{{ product.itemName }}</td>
                    <td>{{ product.itemPrice }}</td>
                    <td>{{ product.description }}</td>
                    <td>{{ product.category }}</td>
                    <td>{{ product.image }}</td>
                    <td>
                        <button @click="openEditModal(product.id)">修改</button>
                        <button @click="deleteProduct(product.id)">删除</button>
                    </td>
                </tr>
            </tbody>
          </table>
        </div>

        

        <div v-if="currentView === 'users'">
          <h3>用户管理</h3>
          <table>
            <thead>
              <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>邮箱</th>
                <th>地址</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in users" :key="user.uid">
                <td>{{ user.uid }}</td>
                <td>{{ user.username }}</td>
                <td>{{ user.email }}</td>
                <td>{{ user.address }}</td>
                <td>
                  <button @click="deleteUser(user.uid)">删除</button>
                  <button @click="fetchUserOrders(user.uid); currentView = 'orderHistory'">
                    查看订单历史</button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
<div v-if="currentView === 'orders'">
  <div style="display: flex; align-items: center; justify-content: space-between;">
    <h3>订单管理</h3>
    <button class="add-product-button" @click="map">销售统计</button>
  </div>
  <table>
    <thead>
      <tr>
        <th>ID</th>
        <th>购买用户</th>
        <th>总金额</th>
        <th>状态</th>
        <th>操作</th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="order in orders" :key="order.id">
        <td>{{ order.id }}</td>
        <td>{{ order.username }}</td>
        <td>{{ order.itemPrice * order.count }}</td>
        <td>{{ order.status === 1 ? '已购买' : '待支付' }}</td>
        <td>
          <button @click="openEditOrderModal(order.id)">编辑</button>
          <button @click="deleteOrder(order.id)">删除</button>
          <button @click="viewOrderDetails(order.id)">查看详情</button>
        </td>
      </tr>
    </tbody>
  </table>
</div>

    <!-- 编辑商品的模态框 -->
    <div v-if="isEditModalOpen" class="modal-overlay">
      <div class="modal-content">
        <h3>编辑商品</h3>
        <form @submit.prevent="updateProduct">
          <input type="text" v-model="editingProduct.itemName" placeholder="商品名称" />
          <input type="text" v-model="editingProduct.itemPrice" placeholder="价格" />
          <input type="text" v-model="editingProduct.description" placeholder="描述" />
          <input type="text" v-model="editingProduct.category" placeholder="类别" />
          <input type="text" v-model="editingProduct.image" placeholder="图片路径" />
          <button type="submit">提交</button>
          <button @click="closeEditModal">取消</button>
        </form>
      </div>
    </div>

    <!-- 添加商品的模态框 -->
<div v-if="isAddModalOpen" class="modal-overlay">
  <div class="modal-content">
    <h3>添加商品</h3>
    <form @submit.prevent="addProduct">
      <input type="text" v-model="newProduct.itemName" placeholder="商品名称" />
      <input type="text" v-model="newProduct.itemPrice" placeholder="价格" />
      <input type="text" v-model="newProduct.description" placeholder="描述" />
      <input type="text" v-model="newProduct.category" placeholder="类别" />
      <input type="text" v-model="newProduct.image" placeholder="图片路径" />
      <button type="submit">提交</button>
      <button @click="closeAddModal">取消</button>
    </form>
  </div>
</div>

  <!-- 订单历史视图 -->
<div v-if="currentView === 'orderHistory'">
  <div class="order-history-page">
    <h2>订单历史</h2>
    <div class="order-summary">
      <div v-if="orderHistoryLoading" class="loading">加载中...</div>
      <div v-else-if="orderHistoryError" class="error">{{ orderHistoryError }}</div>
      <ul v-else class="order-list">
        <li v-for="order in userOrders" :key="order.id" class="order-item">
          <h4>订单号: <span>{{ order.id }}</span></h4>
          <p>下单时间: <span>{{ readableCreateTime(order.createTime) }}</span></p>
          <p>订单状态: <span>{{ orderStatusText(order.status) }}</span></p>
          <ul class="cart-list">
            <li class="cart-item">
              <div class="product-image">
                <img :src="order.image" :alt="order.itemName" style="width: 100px; height: 100px;">
              </div>
              <h3>{{ order.itemName }}</h3>
              <p>单价: {{ order.itemPrice }}</p>
              <p>购买数量: {{ order.count }}</p>
              <p>总计: {{ (order.itemPrice * order.count).toFixed(2) }}</p>
              <!-- 支付按钮可以根据实际情况添加 -->
            </li>
          </ul>
        </li>
      </ul>
    </div>
  </div>
</div>


<!-- 编辑订单的模态框 -->
<div v-if="isEditOrderModalOpen" class="modal-overlay">
  <div class="modal-content">
    <h3>编辑订单</h3>
    <form @submit.prevent="updateOrder">
      <input type="text" v-model="editingOrder.id" placeholder="订单ID" disabled />
      <input type="text" v-model="editingOrder.username" placeholder="购买用户" />
      <input type="text" v-model="editingOrder.totalAmount" placeholder="总金额" />
      <input type="text" v-model="editingOrder.status" placeholder="状态" />
      <button type="submit">提交</button>
      <button @click="closeEditOrderModal">取消</button>
    </form>
  </div>
</div>

<!-- 订单详情的模态框 -->
<div v-if="isOrderDetailsModalOpen" class="modal-overlay">
  <div class="modal-content">
    <h3>订单详情</h3>
    <div class="order-details">
      <ul class="order-list">
        <li class="order-item">
          <h4>订单号: <span>{{ selectedOrder.id }}</span></h4>
          <p>下单时间: <span>{{ readableCreateTime(selectedOrder.createTime) }}</span></p>
          <p>订单状态: <span>{{ orderStatusText(selectedOrder.status) }}</span></p>
          <ul class="cart-list">
            <li class="cart-item">
              <div class="product-image">
                <img :src="selectedOrder.image" :alt="selectedOrder.itemName" style="width: 100px; height: 100px;">
              </div>
              <h3>{{ selectedOrder.itemName }}</h3>
              <p>单价: {{ selectedOrder.itemPrice }}</p>
              <p>购买数量: {{ selectedOrder.count }}</p>
              <p>总计: {{ (selectedOrder.itemPrice * selectedOrder.count).toFixed(2) }}</p>
            </li>
          </ul>
        </li>
      </ul>
    </div>
    <button @click="closeOrderDetailsModal">关闭</button>
  </div>
</div>

<!-- 销售统计视图 -->
<div v-if="isSalesReportModalOpen" class="modal-overlay">
  <div class="modal-content">
    <h3>销售统计</h3>
    <div class="sales-report-charts">
      <canvas id="weeklySalesChart"></canvas>
      <p class="chart-caption">近七日销售额统计图</p>
    </div>
    <button @click="isSalesReportModalOpen = false">关闭</button>
  </div>
</div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, watch, nextTick } from 'vue';
  import instance from '@/utils/request';
  import { Chart, registerables } from 'chart.js';

const { LineController, LineElement, PointElement, 
  LinePlugin, LegendPlugin, 
  TooltipPlugin, FillingPlugin } = registerables;

  Chart.register(...registerables);
  
  const currentView = ref('products');
  const products = ref([]);
  const users = ref([]);
  const orders = ref([]);
  const editingProduct = ref(null); // 状态来跟踪当前正在编辑的商品
  const isEditModalOpen = ref(false);
  // 新增商品的状态
  const isAddModalOpen = ref(false);
  const newProduct = ref({
    itemName: '',
    itemPrice: '',
    description: '',
    category: '',
    image: ''
  });

// 状态来控制销售统计视图的显示
const isSalesReportModalOpen = ref(false);

// 销售统计数据
const salesData = ref({
  weeklySales: [], // 近一周销售额变化数据
  monthlyCategorySales: [] // 一个月内按商品分类销售额数据
});

// 打开销售统计视图
const map =  async () => {
  calculateSales(); // 计算销售额
  //console.log(salesData)
  //console.log(salesData.value.weeklySales);
  //console.log(salesData.value.monthlyCategorySales);
  isSalesReportModalOpen.value = true; // 显示销售统计视图
  await nextTick();
  drawCharts();
};

// 状态来跟踪当前选中的订单
const selectedOrder = ref({});

// 状态来控制订单详情模态框的显示
const isOrderDetailsModalOpen = ref(false);

// 查看订单详情
const viewOrderDetails = (orderId) => {
  // 根据订单 ID 查找订单对象
  const order = orders.value.find(o => o.id === orderId);
  // 检查是否找到了订单对象
  if (!order) {
    console.error('Order not found');
    return;
  }
  // 将找到的订单对象赋值给 selectedOrder
  selectedOrder.value = { ...order };
  // 显示模态框
  isOrderDetailsModalOpen.value = true;
};

// 关闭订单详情模态框
const closeOrderDetailsModal = () => {
  isOrderDetailsModalOpen.value = false;
};

// 状态来跟踪当前正在编辑的订单
const editingOrder = ref({
  id: '',
  username: '',
  itemPrice: '',
  count: '',
  status: ''
});

// 状态来控制编辑订单模态框的显示
const isEditOrderModalOpen = ref(false);

// 打开编辑订单模态框
const openEditOrderModal = (orderId) => {
  // 根据订单 ID 查找订单对象
  const order = orders.value.find(o => o.id === orderId);
  // 检查是否找到了订单对象
  if (!order) {
    console.error('Order not found');
    return;
  }
  // 将找到的订单对象赋值给 editingOrder
  editingOrder.value = { ...order };
  // 显示模态框
  isEditOrderModalOpen.value = true;
};

// 关闭编辑订单模态框
const closeEditOrderModal = () => {
  editingOrder.value = {
    id: '',
    username: '',
    itemPrice: '',
    count: '',
    status: ''
  };
  isEditOrderModalOpen.value = false;
};

  // 订单历史相关的状态
const orderHistoryLoading = ref(false);
const orderHistoryError = ref(null);
const userOrders = ref([]);

// 获取用户订单历史的方法
const fetchUserOrders = async (userId) => {
  if (!userId) {
    console.error('User ID is required to fetch orders');
    return;
  }
  //console.log(userId)
  orderHistoryLoading.value = true;
  orderHistoryError.value = null;
  try {
    const response = await instance.get(`http://8.219.49.219:8080/onlineShopping/shoppingCar/getOrdersByUser/${userId}`);
    userOrders.value = response.data.data.sort((a, b) => new Date(b.createTime) - new Date(a.createTime));
  } catch (err) {
    orderHistoryError.value = err.message;
  } finally {
    orderHistoryLoading.value = false;
  }
};
  
  
  const fetchProducts = async () => {
    try {
      const response = await instance.get('http://8.219.49.219:8080/onlineShopping/item/items');
      products.value = response.data.data;
    } catch (error) {
      console.error('Error fetching products:', error);
    }
  };
  
  const fetchUsers = async () => {
    try {
      const response = await instance.get('http://8.219.49.219:8080/onlineShopping/user/users');
      users.value = response.data.data;
    } catch (error) {
      console.error('Error fetching users:', error);
    }
  };
  
  const fetchOrders = async () => {
    try {
      const response = await instance.get('http://8.219.49.219:8080/onlineShopping/shoppingCar/getAllOrders');
      orders.value = response.data.data;
    } catch (error) {
      console.error('Error fetching orders:', error);
    }
  };
  
const deleteProduct = async (id) => {
    if (window.confirm('确定要删除这个商品吗？')) {
      //console.log(id)
        try {
            await instance.delete(`http://8.219.49.219:8080/onlineShopping/item/deleteItem/${id}`);
            fetchProducts(); 
            alert('商品删除成功'); 
        } catch (error) {
            console.error('Error deleting product:', error);
        }
    } else {
        console.log('删除操作已取消');
    }
};
  
  const deleteUser = async (uid) => {
    if (window.confirm('确定要删除这个用户吗？')) {
      //console.log(uid)
        try {
            await instance.delete(`http://8.219.49.219:8080/onlineShopping/user/deleteUser/${uid}`);
            fetchUsers(); 
            alert('用户删除成功'); 
        } catch (error) {
            console.error('Error deleting user:', error);
        }
    } else {
        console.log('删除操作已取消');
    }
  };

  const openEditModal = (productId) => {
  // 根据商品 ID 查找商品对象
  const product = products.value.find(p => p.id === productId);
  // 检查是否找到了商品对象
  if (!product) {
    console.error('Product not found');
    return;
  }
  // 将找到的商品对象赋值给 editingProduct
  editingProduct.value = { ...product };
  
  // 显示模态框
  isEditModalOpen.value = true;
};
const closeEditModal = () => {
  editingProduct.value = null;
  isEditModalOpen.value = false;
};

const updateProduct = async () => {
  try {
    //console.log(editingProduct.value)
    await instance.put(`http://8.219.49.219:8080/onlineShopping/item/updateItem/${editingProduct.value.id}`, editingProduct.value);
    const index = products.value.findIndex(p => p.id === editingProduct.value.id);
    if (index !== -1) {
      // 更新找到的商品信息
      products.value[index] = { ...editingProduct.value };    
    }
    closeEditModal();
  } catch (error) {
    console.error('Error updating product:', error);
  }
};

// 打开添加商品模态框
const openAddModal = () => {
  isAddModalOpen.value = true;
};

// 关闭添加商品模态框
const closeAddModal = () => {
  isAddModalOpen.value = false;
  newProduct.value = {
    itemName: '',
    itemPrice: '',
    description: '',
    category: '',
    image: ''
  };
};

// 添加商品
const addProduct = async () => {
  try {
    await instance.post('http://8.219.49.219:8080/onlineShopping/item/add', newProduct.value);
    fetchProducts(); // 重新获取商品列表
    closeAddModal(); // 关闭模态框
    alert('商品添加成功'); 
  } catch (error) {
    console.error('Error adding product:', error);
  }
};

    const readableCreateTime = (createTime) => {
            const date = new Date(createTime);
            const datePart = date.toLocaleDateString('zh-CN', {
                year: 'numeric',
                month: '2-digit',
                day: '2-digit'
            });
            const timePart = date.toLocaleTimeString('zh-CN', {
                hour: '2-digit',
                minute: '2-digit',
                hour12: false
            });
            return `${datePart} ${timePart}`;
        };

const orderStatusText = (status) => {
    return status === 1 ? '已购买' : '待支付';
};

// 计算销售额
const calculateSales = () => {
  //console.log('111')
  const oneDay = 24 * 60 * 60 * 1000; // 一天的毫秒数
  const sevenDaysAgo = new Date().getTime() - 7 * oneDay; // 7天前的日期
  // const thirtyDaysAgo = new Date().getTime() - 30 * oneDay; // 30天前的日期

  let weeklySales = [];
  // let monthlyCategorySales = {};

  orders.value.forEach(order => {
    const orderDate = new Date(order.createTime).getTime();

    // 计算近7日销售额
    if (orderDate > sevenDaysAgo) {
      const sum = order.itemPrice * order.count;
      weeklySales.push({ date: order.createTime, sales: sum });
    }

    // // 计算一个月内按商品分类销售额
    // if (orderDate > thirtyDaysAgo) {
    //   const category = order.category;
    //   //console.log(category)
    //   if (!monthlyCategorySales[category]) {
    //     monthlyCategorySales[category] = { category, sales: 0 };
    //   }
    //   monthlyCategorySales[category].sales += order.itemPrice * order.count;
    // }
  });

  // 转换monthlyCategorySales为数组
  salesData.value.weeklySales = weeklySales;
  // salesData.value.monthlyCategorySales = Object.values(monthlyCategorySales);
  //console.log('222')
  //console.log(salesData.value)
};

const drawCharts = () => {
  //console.log("Drawing charts with data:", salesData.value);
  const ctxWeekly = document.getElementById('weeklySalesChart').getContext('2d');

  // 将日期和销售额分别存储在两个数组中
  const dates = salesData.value.weeklySales.map(data => new Date(data.date).toLocaleDateString());
  const sales = salesData.value.weeklySales.map(data => data.sales);

  // 使用Map来合并同一天的销售额
  const salesMap = new Map();
  dates.forEach((date, index) => {
    if (salesMap.has(date)) {
      // 如果已经存在这一天，累加销售额
      salesMap.set(date, salesMap.get(date) + sales[index]);
    } else {
      // 否则，设置这一天的销售额
      salesMap.set(date, sales[index]);
    }
  });

  // 从Map中提取合并后的日期和销售额
  const labels = Array.from(salesMap.keys());
  const dataset = Array.from(salesMap.values());

  new Chart(ctxWeekly, {
    type: 'line',
    data: {
      labels: labels,
      datasets: [{
        label: '销售额',
        data: dataset,
        borderColor: 'rgb(75, 192, 192)',
        backgroundColor: 'rgba(75, 192, 192, 0.2)',
      }]
    },
    options: {
      responsive: true,
      // ...其他配置
    }
  });
};

  onMounted(() => {
    fetchProducts();
    fetchUsers();
    fetchOrders();
  });
  </script>
  
  <style scoped>
 .management-container {
  display: flex;
  height: 100vh;
  background-color: rgba(255, 255, 255, 0.8);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  color: #333;
  background-size: cover;
  background-position: center;
  background-blend-mode: multiply;
}

.sidebar {
  width: 120px;
  padding: 20px;
  border-right: 1px solid #ccc;
  text-align: center;
  background-color: #f9f9f9;
  height: 100%;
  position: fixed; 
  overflow-y: auto; 
}

.sidebar h2 {
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
  font-family: 'Roboto', sans-serif;
}

.sidebar nav {
  margin-bottom: 20px;
}

.sidebar nav button {
  margin: 10px 0;
  padding: 10px 20px;
  width: 100%;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
}

.sidebar nav button:hover {
  background-color: #45a049;
}

.content {
  flex: 1;
  padding: 20px;
  text-align: left;
  margin-left: 160px; 
  overflow-y: auto;
  height: calc(100vh - 40px); 
}

table {
  width: 100%;
  border-collapse: collapse;
  margin-bottom: 20px;
}

table th, table td {
  padding: 10px;
  border: 1px solid #ccc;
  text-align: left;
  min-width: 120px;
}

table th {
  background-color: #f2f2f2;
  font-weight: bold;
}

table tr:nth-child(even) {
  background-color: #f9f9f9;
}

table tr:hover {
  background-color: #f1f1f1;
}

table button {
  padding: 5px 10px;
  background-color: #ff4d4d;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.3s ease;
  margin: 5px;
}

table button:hover {
  background-color: #e53935;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  max-width: 500px;
  width: 100%;
}

.modal-content input {
  display: block;
  margin: 10px 0;
  padding: 10px;
  width: 100%;
  box-sizing: border-box;
}

.modal-content button {
  padding: 10px 20px;
  background-color: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease;
  margin: 10px;
}

.modal-content button:hover {
  background-color: #45a049;
}

/* 添加商品按钮 */
.add-product-button {
  padding: 10px 20px;
  border: none;
  border-radius: 20px; 
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.3s ease, box-shadow 0.3s ease;
  outline: none;
  color: #fff;
  background-color: #007BFF;
  box-shadow: 0 4px 8px rgba(0, 123, 255, 0.3);
  text-decoration: none;
  display: inline-block;
  text-align: center;
  margin-left: 20px; 
}

.add-product-button:hover {
  background-color: #0056b3;
  box-shadow: 0 6px 12px rgba(0, 123, 255, 0.3);
}

.order-history-page {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  margin: 20px;
}

.order-history-page {
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  margin: 20px;
}

.order-history-page h2 {
  color: #333;
  font-size: 24px;
  margin-bottom: 20px;
}

.order-summary {
  background-color: white;
  padding: 20px;
  border-radius: 6px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.order-list {
  list-style: none;
  padding: 0;
}

.order-item {
  border-bottom: 2px solid #e0e0e0; /* 增加边框宽度 */
  padding: 15px 0;
}

.order-item:last-child {
  border-bottom: none;
}

.cart-list {
  list-style: none;
  padding: 0;
}

.cart-item {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.product-image img {
  border-radius: 4px;
  margin-right: 15px;
}

.order-item h4, .order-item p {
  margin: 8px 0; 
}

.order-item h4 span, .order-item p span {
  font-weight: bold;
}
.cart-item h4, .cart-item p {
  margin: 8px 0; 
  padding-left: 15px; 
  padding-right: 15px; 
}

.loading, .error {
  text-align: center;
  padding: 20px;
  background-color: #f2f2f2;
  border-radius: 4px;
  margin-top: 20px;
}

.loading {
  color: #555;
}

.error {
  color: #d9534f;
}

.chart-caption {
  text-align: center;
  font-size: 14px;
  color: #666;
  margin-top: 10px;
}

</style>
  